<?php

class AlbumController extends Controller
{
	public $layout = 'awt';
	
	public function actionIndex()
	{
		$this->render('index');
	}
	
	public function actionSearch() {
		
		//$_GET['name'] = 'a';
		
		# page init
		$page = (isset($_GET['page']))?$_GET['page']:1;
		$page = ($page <=0 ) ? 1 : $page;
		
		# order init
		$order = (isset($_GET['order']))?$_GET['order']:'date_create desc';
		
		#condition init
		$condition = array();
		$filter = array('artist_id','name');
		foreach ($filter as $key) {
			if (isset($_GET[$key])&&!empty($_GET[$key])) {
				$condition[$key] = $_GET[$key];
			}
		}
		
		
		$rs = AlbumInterface::search(
			$condition,
			$page,
			$order,
			Yii::app()->params['paging']['pageSize']
		);
		$this->render('search',array(
			'rs'=>$rs,
		));

	}
	
	public function actionQuickview($id) {
		
		$this->layout = 'awt-quickview';
		
		$rs = Reference::model()->with('album')->findByPk($id);
		
		$this->render('quickview',array(
			'rs'	=>$rs
		));
	}
	
	public function actionCreate() {
		
		$model = new Album();
		
		if ( !empty($_POST) && isset($_POST['Album']) ) {
			
			$model->attributes = $_POST['Album'];
			if ($model->save()) {
				
				Yii::app()->user->setFlash('success',"Data saved!");
			} else {
				echo "<pre>"; print_r( $model->getErrors() ); exit;
				Yii::app()->user->setFlash('error',"There is an Error");
			}
			$this->refresh();
		}
		
		$this->render('create',array(
			'model'=>$model,
		));
	}
	
	public function actionUpdate($id) {
		
		$model = new Album('update');
		$model = $model->findByPk($id);

		if ( !empty($_POST) && isset($_POST['Album']) ) {
			
			$model->attributes = $_POST['Album'];
			if ($model->save()) {
				Yii::app()->user->setFlash('success',"Data saved!");
			} else {
				echo "<pre>"; print_r( $model->getErrors() ); exit;
			}
			$this->refresh();
		}
		$this->render('create',array(
			'model'=>$model,
		));
	}
	
	public function actionDelete() {
		
		if ( !empty($_POST) && isset($_POST['Reference']) ) {
			$rs = Reference::model()->deleteByPk($_POST['Reference']['id']);
			if ($rs) {
				Yii::app()->user->setFlash('success',"Reference Deleted");
			} else {
				echo "<pre>"; print_r( $rs->getErrors() ); exit;
				Yii::app()->user->setFlash('error',"There is an Error");
			}
		}
		$this->redirect(Yii::app()->request->getUrlReferrer());
	}
}